package cn.itcast.wanxinp2p.consumer.controller;

import cn.itcast.wanxinp2p.account.model.LoginUser;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.util.EncryptUtil;
import cn.itcast.wanxinp2p.consumer.ConsumerApi;
import cn.itcast.wanxinp2p.consumer.model.ConsumerRegisterDTO;
import cn.itcast.wanxinp2p.consumer.model.ConsumerRequest;
import cn.itcast.wanxinp2p.consumer.service.ConsumerService;
import cn.itcast.wanxinp2p.depository.GatewayRequest;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/consumer")
@Api(value = "用户服务的Controller", tags = "Consumer", description = "用户服务API")
    public class ConsumerController  implements ConsumerApi {
    @Resource
    private  RedisTemplate<String,String> redisTemplate;
    @Autowired
    private ConsumerService consumerService;
    @Override
    @ApiOperation("用户注册")
    @PostMapping(value = "/consumers")
    public RestResponse register(@RequestBody ConsumerRegisterDTO consumerRegisterDTO) {
      System.out.println("cucucucuu"+consumerRegisterDTO);

        consumerService.register(consumerRegisterDTO);
        return RestResponse.success();
    }

    @ApiOperation("生成开户请求数据")
    @ApiImplicitParam(name = "consumerRequest", value = "开户信息", required = true, dataType = "ConsumerRequest", paramType = "body")
    @PostMapping("/my/consumers")
    public RestResponse<GatewayRequest> createConsumer(@RequestHeader(value = "Authorization",required = false) String value,@RequestBody ConsumerRequest consumerRequest) {
      System.out.println(consumerRequest.getMobile()+"......");
        String s = redisTemplate.opsForValue().get(value);
        LoginUser user = JSON.parseObject(s, LoginUser.class);
        System.out.println(user+".........user");
        consumerRequest.setMobile(user.getMobile());
        return consumerService.createConsumer(consumerRequest);
    }


    @ApiOperation("过网关受保护资源，进行认证拦截测试")
    @ApiImplicitParam(name = "jsonToken", value = "访问令牌", required = true,
            dataType = "String")
    @GetMapping(value = "/m/consumers/test")
    public RestResponse<String> testResources(String jsonToken) {
        return RestResponse.success(EncryptUtil.decodeUTF8StringBase64(jsonToken));
    }
}
